import { parse } from "querystring";
import { MockMethod } from "vite-plugin-mock";
import client_token from "./client_token.json";
import custom_token from "./custom_info.json";
import { requestParams, resultSuccess } from "./util";

console.log("use mock data...");

const API_HOST = "/api";

const token = {
  access_token: "mock_access_token",
  token_type: "bearer",
  refresh_token: "mock_refresh_token",
  expires_in: 43200,
  scope: "read write",
  tenancyId: "-9223372036854775808",
  roles: ["ROLE_ADMIN", "ROLE_SUPERADMIN"],
  userName: "ZWD284", // "admin",
  userId: "0",
  jti: "d703bbd7-e018-42f3-9e1b-083735da7230",
};

const users = {
  admin: {
    id: "376037655202234368",
    loginName: "admin",
    name: "系统管理员",
    email: "admin@qq.com",
    telephone: "12589628953",
    description: "住院部主任",
  },
  demo: {
    id: "376037655202234369",
    loginName: "ZWD284",
    name: "赵卫东",
    email: "demo@qq.com",
    telephone: "12589628952",
    description: "demo--xxxx,odoos",
  },
};

export default [
  {
    // 登录 or 获取 clientToken
    url: "/api/authserver/oauth/token",
    method: "post",
    timeout: 1000,
    rawResponse: async (req, res) => {
      // body :  username=admin&password=123&grant_type=password

      let reqbody = "";
      await new Promise((resolve) => {
        req.on("data", (chunk) => {
          reqbody += chunk;
        });
        req.on("end", () => resolve(undefined));
      });

      console.log("[ mock ] body : ", reqbody);
      const params = parse(reqbody);
      console.log("[ mock ] params : ", params);

      const { grant_type } = params;

      if (grant_type === "client_credentials") {
        res.end(JSON.stringify(client_token));
        return;
      }

      const { username } = params;

      if (username === "user400") {
        res.statusCode = 400;
        res.end(
          JSON.stringify({
            exception: "登录失败 400，用户名或密码错误，注意登录次数限制",
          }),
        );
        return;
      }

      const user = users[username as keyof typeof users];
      console.log("[ mock ] user ", user);

      if (!user) {
        console.log("[ mock ] no user");
        res.statusCode = 401;
        res.end(
          JSON.stringify({
            code: "ERROR",
            exception: "登录失败 401，用户名或者密码错误",
          }),
        );
        return;
      }

      res.end(JSON.stringify(token));
      return;
    },
  },
  // {
  //   url: "/api/authserver/oauth/token2",
  //   timeout: 1000,
  //   method: "post",
  //   response: (req: requestParams) => {
  //     // body :  username=admin&password=123&grant_type=password

  //     console.log("auth url param is :", req);

  //     const { username } = req.query.body;
  //     console.log("[ mock ] username : ", username);

  //     if (username === "user400") {
  //       return {
  //         code: 400,
  //         exception: "登录失败，密码错误，注意登录次数限制",
  //       };
  //     }

  //     return {
  //       token,
  //     };
  //   },
  // },
  {
    url: `${API_HOST}/manager/medical-staff/staff-info-His`,
    method: "get",
    response: () => {
      return resultSuccess(users["admin"]);
    },
  },
  {
    url: `${API_HOST}/manager/biz-config/query-biz-config`,
    method: "get",
    response: (req: requestParams) => {
      console.log("url param is :", req);
      // ?app=manager&scopeOwnerIdMap=&varName=CustomInfo
      return resultSuccess(custom_token);
    },
  },
] as MockMethod[];
